import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, ScrollView, TextInput, Image } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { searchBooks } from '../src/services/bookService';

const CategoryMain = ({ navigation }) => {
  const [searchText, setSearchText] = useState('');
  const [categoryBooks, setCategoryBooks] = useState({});
  const [loading, setLoading] = useState(true);

  const categories = [
    { id: '1', name: '玄幻奇幻' },
    { id: '2', name: '武侠仙侠' },
    { id: '3', name: '都市言情' },
    { id: '4', name: '历史军事' },
    { id: '5', name: '网游竞技' },
    { id: '6', name: '科幻灵异' },
  ];

  useEffect(() => {
    fetchCategoryBooks();
  }, []);

  const fetchCategoryBooks = async () => {
    try {
      const booksMap = {};
      for (const category of categories) {
        const data = await searchBooks({ category: category.name });
        if (data && data.length > 0) {
          // 随机选择一本该分类的书
          const randomIndex = Math.floor(Math.random() * data.length);
          booksMap[category.name] = data[randomIndex];
        }
      }
      setCategoryBooks(booksMap);
      setLoading(false);
    } catch (error) {
      console.error('Error fetching category books:', error);
      setLoading(false);
    }
  };

  const handleSearch = () => {
    if (searchText.trim()) {
      navigation.navigate('Search', { keyword: searchText.trim() });
      setSearchText('');
    }
  };

  const renderCategory = ({ item }) => {
    const book = categoryBooks[item.name];

    return (
      <TouchableOpacity
        style={styles.categoryContainer}
        onPress={() => navigation.navigate('Search', { category: item.name })}
      >
        {book && (
          <>
            <Text style={styles.categoryTitle}>{item.name}</Text>
            <View style={styles.bookInfo}>
              <Image
                source={{ uri: book.image || 'https://via.placeholder.com/150x200/e0e0e0/757575?text=Book' }}
                style={styles.bookCover}
              />
              <View style={styles.textContainer}>
                <Text style={styles.bookTitle} numberOfLines={1}>{book.title}</Text>
                <Text style={styles.bookAuthor} numberOfLines={1}>{book.author}</Text>
              </View>
            </View>
          </>
        )}
      </TouchableOpacity>
    );
  };

  return (
    <View style={styles.container}>
      <View style={styles.searchBar}>
        <TouchableOpacity onPress={handleSearch} style={styles.searchIcon}>
          <Icon name="search" size={20} color="#999" />
        </TouchableOpacity>
        <TextInput
          style={styles.searchInput}
          placeholder="搜索书籍"
          placeholderTextColor="#999"
          value={searchText}
          onChangeText={setSearchText}
          onSubmitEditing={handleSearch}
          returnKeyType="search"
        />
        {searchText ? (
          <TouchableOpacity onPress={() => setSearchText('')}>
            <Icon name="times-circle" size={18} color="#999" style={styles.clearIcon} />
          </TouchableOpacity>
        ) : null}
      </View>
      <ScrollView style={styles.scrollContainer}>
        <FlatList
          data={categories}
          renderItem={renderCategory}
          keyExtractor={(item) => item.id}
          scrollEnabled={false}
          numColumns={2}
          contentContainerStyle={styles.listContainer}
        />
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  searchBar: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
    borderRadius: 20,
    paddingHorizontal: 15,
    paddingVertical: 10,
    margin: 15,
    marginTop: 50,
  },
  searchIcon: {
    marginRight: 10,
    padding: 5,
  },
  searchInput: {
    flex: 1,
    fontSize: 16,
    color: '#333',
    padding: 0,
  },
  clearIcon: {
    marginLeft: 10,
    padding: 5,
  },
  scrollContainer: {
    flex: 1,
  },
  listContainer: {
    padding: 10,
  },
  categoryContainer: {
    flex: 1,
    backgroundColor: '#fff',
    borderRadius: 8,
    margin: 5,
    padding: 12,
    elevation: 2,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.2,
    shadowRadius: 2,
  },
  categoryTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 12,
  },
  bookInfo: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  bookCover: {
    width: 80,
    height: 110,
    borderRadius: 4,
    marginRight: 12,
  },
  textContainer: {
    flex: 1,
    height: 110,
    justifyContent: 'center',
  },
  bookTitle: {
    fontSize: 14,
    color: '#666',
    marginBottom: 4,
  },
  bookAuthor: {
    fontSize: 12,
    color: '#999',
  }
});

export default CategoryMain;